// cloudfunctions/deletePost/index.js
const cloud = require('wx-server-sdk');
cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
  })
const db = cloud.database();

exports.main = async (event, context) => {
  try {
    const { postId,userInfo } = event;
    if (!postId) {
      return { success: false, message: '缺少postId参数' };
    }
    
    if (!userInfo) {
      return { success: false, message: '未登录' };
    }
    
    // 检查帖子是否存在且属于当前用户
    const postResult = await db.collection('community_posts').doc(postId).get();
    if (!postResult.data) {
      return { success: false, message: '帖子不存在' };
    }
    
    const post = postResult.data;
    if (post.userId !== userInfo._id) {
      return { success: false, message: '没有权限删除此帖子' };
    }
    
    // 删除帖子
    await db.collection('community_posts').doc(postId).update({
      data: {
        status: 'deleted'
      }
    });
    
    return {
        success: true,
        message: '删除帖子成功'
      };
    } catch (error) {
      console.error('删除帖子失败', error);
      return {
        success: false,
        message: error.message || '服务器错误',
        error: error.message
      };
    }
  };